package com.training.service;

import java.sql.SQLException;
import com.training.model.User;
import com.training.api.dto.LoginRequest;
import com.training.api.dto.LoginResponse;
import com.training.util.JwtUtil;
import com.training.dao.DatabaseInitializer;
import com.training.dao.UserDao;

public class UserService {
    private final UserDao userDao;

    public UserService() {
        this.userDao = new UserDao();
        
        // 初始化数据库（包括用户表）
        DatabaseInitializer initializer = new DatabaseInitializer();
        initializer.initializeDatabase();
    }

    public User findByUsername(String username) {
        try {
            return userDao.findByUsername(username);
        } catch (SQLException e) {
            throw new RuntimeException("Error finding user by username", e);
        }
    }

    public LoginResponse login(LoginRequest request) {
        User user = findByUsername(request.getUsername());
        
        if (user == null || !validatePassword(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("Invalid username or password");
        }

        LoginResponse response = new LoginResponse();
        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setRealName(user.getRealName());
        response.setToken(JwtUtil.generateToken(user.getUsername(), user.getId()));

        return response;
    }

    public User createUser(String username, String password, String realName) {
        try {
            // 检查用户名是否已存在
            if (userDao.existsByUsername(username)) {
                throw new RuntimeException("Username already exists");
            }
            return userDao.create(username, password, realName);
        } catch (SQLException e) {
            throw new RuntimeException("Error creating user", e);
        }
    }

    public boolean deleteUser(long id) {
        try {
            return userDao.deleteById(id);
        } catch (SQLException e) {
            throw new RuntimeException("Error deleting user", e);
        }
    }

    public boolean userExists(long id) {
        try {
            return userDao.existsById(id);
        } catch (SQLException e) {
            throw new RuntimeException("Error checking if user exists", e);
        }
    }

    private boolean validatePassword(String inputPassword, String storedPassword) {
        // TODO: 实现密码验证逻辑，应该使用加密后的密码比较
        return inputPassword.equals(storedPassword);
    }
}
